package com.springboot.redis.service.impl;

import com.springboot.redis.mapper.UserMapper;
import com.springboot.redis.model.User;
import com.springboot.redis.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

/**
 * @author liuwei
 * @version 2017/7/16 上午11:23
 * @modified TODO
 * @description 功能描述
 * @see
 * @since 1.0
 */
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate<Long , User> redisTemplate;

    @Override
    public User findById(Long id) {
        ValueOperations<Long , User> ops = redisTemplate.opsForValue();
        User user = ops.get(id);
        if (user != null){
            System.out.println("从redis中获取数据:" + id);
            return user;
        }
        user = userMapper.findById(id);
        if (user != null){
            ops.set(id , user);
        }
        return user;
    }

    @Override
    public Long save(User user) {
        if(userMapper.save(user) > 0){
            redisTemplate.opsForValue().set(user.getId() , user);
            return user.getId();
        }
        return 0L;
    }

    @Override
    public Boolean update(User user) {
        if (userMapper.update(user) > 0){
            redisTemplate.opsForValue().set(user.getId() , user);
            return true;
        }
        return false;
    }

    @Override
    public Boolean remove(Long id) {
        return null;
    }
}
